package com.qk.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.aop.anno.Cacheable;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author 28188
 */
@Slf4j
@Aspect
@Component
public class CacheableAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    @Pointcut("@annotation(com.qk.aop.anno.Cacheable)")
    public void cacheable() {
    }

    @Around("cacheable()")
    public Object cacheable(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result;
        String redisKey = null;
        long expireTime = 0L;
        TimeUnit expireTimeUnit = null;

        try {
            // 获取方法名称
            String methodName = joinPoint.getSignature().getName();
            // 获取方法
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            // 根据方法获取注解
            Cacheable annotation = method.getAnnotation(Cacheable.class);
            // 从注解中获取参数
            redisKey = annotation.keyPrefix() + methodName;
            expireTime = annotation.expireTime();
            expireTimeUnit = annotation.expireTimeUnit();
            // 获取缓存
            String jsonStr = Objects.requireNonNull(redisTemplate.opsForValue().get(redisKey)).toString();
            if (ObjectUtil.isNotEmpty(jsonStr)) {
                return JSONUtil.toBean(jsonStr, method.getReturnType());
            }
        } catch (Exception e) {
            log.error("暂无缓存数据:{}", e.getMessage());
        }
        // 缓存未命中
        try {
            result = joinPoint.proceed();
        } catch (Exception e) {
            log.error("获取数据异常:{}", e.getMessage());
            throw new RuntimeException(e);
        }
        // 将数据加入缓存
        try {
            redisTemplate.opsForValue().set(redisKey, JSONUtil.toJsonStr(result), expireTime, expireTimeUnit);
        } catch (Exception e) {
            log.error("未获取到缓存数据:{}", e.getMessage());
        }
        return result;
    }
}
